<?php
/*
 * @Date: 2020-04-28 19:14:47
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-09-13 22:13:21
 * @FilePath: /Site/app/api/common.php
 */
// 这是系统自动生成的公共文件

use think\facade\Db;
use think\facade\Request;
//api请求成功返回
function successJsonReturn($uccessData = [], $message = "success", $uccessCode = 200)
{
    switch ($uccessCode) {
        case 200:
            $return_data = ["code" => 200, "message" => $message, "data" => $uccessData];
            break;
    }
    return json($return_data);
}
function errorJsonReturn($errorType = "Other-A*00009", $detail = false, $errorCode = 0, $data = [], $panic = true)
{
    $language = Request::header('Accept-Language'); //语言地区

    switch ($language) {
        case 'zh-cn': //中文
            $language = 'lanZhCn';
            break;
        case 'ja-jp': //日语
            $language = 'lanJaJp';
            break;
        case 'zh-tw': //繁体中文
            $language = 'lanZhCn';
            break;
        case 'en-us': //英语
            $language = 'lanEnUs';
            break;
        default: //默认
            $language = 'lanJaJp';
            break;
    }




    $msg = config("$language.$errorType");
    if ($msg) {
        $return_data = json([ //超时
            "code" => $errorType,
            "error" => config("$language.$errorType"),
            "panic" => $panic,
            "data" => $data,
            "detail" => $detail ? $detail : ':(',
        ]);
    } else {
        $return_data = json([
            "code" => $errorCode,
            "error" => $errorType,
            "panic" => true,
            "data" => $data,
            "detail" => $detail ? $detail : '未定义错误',
        ]);
    }

    return $return_data;
}
/**
 * 字符串去除空格
 *
 * @param String $str
 * @return String
 */
function ClearHtml($str) //去空格
{
    $str = trim($str); //清除字符串两边的空格
    $str = strip_tags($str, ""); //利用php自带的函数清除html格式
    $str = preg_replace("/\t/", "", $str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/", "", $str);
    $str = preg_replace("/\r/", "", $str);
    $str = preg_replace("/\n/", "", $str);
    $str = preg_replace("/ /", "", $str);
    $str = preg_replace("/  /", "", $str);  //匹配html中的空格
    return trim($str); //返回字符串
}
/**
 * 生成随机id
 *
 * @param Int $randType 数据类型 
 * !0 user 表 id
 * !1 like 表 id
 * !2 user_view_history 表 id
 * !3 评论 表 id
 * !4 子评论 表 id
 * !5 评论喜欢 表 id
 * @param Int $length 长度 默认22
 * @return String 数据
 */
function randIdStructure($randType, $length = 22)
{


    $stateString = null;
    switch ($randType) {
        case 0: // 用户id
            $stateString = config('apiconfig.UserIdentification') . "-";
            break;
        case 1: // 喜欢id
            $stateString = config('apiconfig.LikeIdentification') . "-";
            break;
        case 2: // 历史记录
            $stateString = config('apiconfig.UserViewHistory') . "-";
            break;
        case 3: //@m 发布评论
            $stateString = config('apiconfig.Comment') . "-";
            break;
        case 4: //@m 发布子评论
            $stateString = config('apiconfig.SonComment') . "-";
            break;
        case 5: //@m 评论喜欢
            $stateString = config('apiconfig.CommentLike') . "-";
            break;
        default:
            $stateString = "";
            break;
    }
    $stateString .= str_rand($length - strlen($stateString));
    return $stateString;
}
function str_rand($length, $char = '0123456789abcdefghijklmnopqrstuvwxyz')
{
    if (!is_int($length) || $length < 0) {
        return false;
    }

    $string = '';
    for ($i = $length; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }

    return $string;
}

/**
 * @desc im:十进制数转换成三十六机制数
 * @param (int)$num 十进制数
 * return 返回：三十六进制数
 */
function get_char($num)
{
    $num = intval($num);
    if ($num <= 0)
        return false;
    $charArr = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    $char = '';
    do {
        $key = ($num - 1) % 36;
        $char = $charArr[$key] . $char;
        $num = floor(($num - $key) / 36);
    } while ($num > 0);
    return $char;
}

/**
 * 验证请求url
 *
 * @param 私钥 先从验证app版本获取 $private_key
 * @param 是否启用debug $debug
 *  $appState  = VerifyAppStatus();//验证app版本
 *  if ($appState['code'] != 200) { //判断 app验证是否异常 
 *      #异常直接返回
 *      return json($appState);
 *  }
 *  $requestState =  UserRequestParameterValidation($appState['private_key']); //获取请求状态 200成功
 *  if ($requestState['code'] != 200) { //验证请求参数
 *      return json($requestState);
 *  }
 * @return json
 */
function UserRequestParameterValidation($private_key, $debug = false) //用户请求参数验证
{


    /**验证方式
     * 吧以下数据加入到一个json
     * json_encode([
    "time" => $time,
    "apiKey" => $apiKey,
    "nonce" => $nonce,
    "appPlatform" => $appPlatform,
    "language" => $language,
    "authorization" => $authorization,
    "appVersion" => $appVersion,
    "appBuildVersion" => $appBuildVersion,
    "appUUID" => $appUUID,
    "requestFunction" => $requestFunction,
     *])
     * 然后进行sha512 密钥为 config('apiconfig.RequestToVerifyEncryptionKey')
     * 再然后 吧上面 sha512的数据 在进行sha256 密钥为 $private_key
     */


    $time = Request::header('time'); //时间戳
    $apiKey = Request::header('api-key'); //接口密钥
    $nonce = Request::header('nonce'); //!随机字符串
    $appPlatform = Request::header('app-platform'); //app类型 ios android
    $source = Request::header('source'); //弃用
    $language = Request::header('Accept-Language'); //语言地区
    $signature = Request::header('signature'); //*签名
    $authorization = Request::header('Authorization'); //用户token
    $appBuildVersion = Request::header('app-build-version'); //app编译版本
    $appUUID = Request::header('app-uuid'); //app的id
    $appVersion = Request::header('app-version'); //app的版本号
    $requestFunction = Request::pathinfo(); //!请求的路径
    /**request 应该有 
  ["app-build-version"] => string(2) "33"
  ["authorization"] => string(321) "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YWYzOTNhN2RiOTFkMDJjODNkOTg3YjQiLCJlbWFpbCI6IjIwMjE4NDE5OSIsInJvbGUiOiJtZW1iZXIiLCJuYW1lIjoi6Z6g6ICA5paMIiwidmVyc2lvbiI6IjIuMS4yLjQiLCJidWlsZFZlcnNpb24iOiIzMyIsInBsYXRmb3JtIjoiaW9zIiwiaWF0IjoxNTkwNjkwODIwLCJleHAiOjE1OTEyOTU2MjB9.FC2evwFzirKLpQM1Vn3jcvX_Vi65C6DrirNO1CnqP6Y"
  ["app-version"] => string(7) "2.1.2.4"
  ["nonce"] => string(32) "5D389E185C9841269F5FE334667D2309"
  ["time"] => string(10) "1592923179"
  ["api-key"] => string(29) "2587EFC6F859B4E3A1D8B6D33B272"
  ["app-platform"] => string(3) "ios"
  ["source"] => string(0) ""//!没有用
  ["accept-language"] => string(5) "zh-cn"
  ["signature"] => string(128) "598cbb30bf7884aa37ab0c558f6903b48770b0c701d9002be8b3a97eb0f3ec9cd6610e4e034642af869b330ab45e8fa54ae785ec25c9a63086f981323325101c"
  ["app-uuid"] => string(36) "D8D0C193-E4E4-440F-A1D1-2DC9E8EBB5F5"
     */
    if (
        !$time ||
        !$apiKey ||
        !$nonce ||
        !$appPlatform ||
        !$language ||
        !$signature ||
        !$authorization ||
        !$appVersion ||
        !$appBuildVersion ||
        !$appUUID
    ) {
        return json_decode(errorJsonReturn('Other-A*00008')->getContent(), true);
    }
    if (config('apiconfig.OpenOrNotRequestTimeOut')) {
        # 是否超时验证
        if ($time + config("apiconfig.RequestTimeOut") <= time()) { //验证是否超时
            return json_decode(errorJsonReturn('Other-A*00009')->getContent(), true);
        }
    }

    $ToBeVerified = json_encode([
        "time" => $time,
        "apiKey" => $apiKey,
        "nonce" => $nonce,
        "appPlatform" => $appPlatform,
        "language" => $language,
        "authorization" => $authorization,
        "appVersion" => $appVersion,
        "appBuildVersion" => $appBuildVersion,
        "appUUID" => $appUUID,
        "requestFunction" => str_replace("/", "-", $requestFunction),
    ]);
    $Verified =  hash_hmac('sha512', hash_hmac('sha512', $ToBeVerified, config('apiconfig.RequestToVerifyEncryptionKey')), $private_key);
    if ($Verified != $signature) { //如果是这里 就是验证不通过
        if ($debug) {
            dump("理想的哈希 $Verified");
            dump("requestFunction 信息 $requestFunction");
        }
        return json_decode(errorJsonReturn('Other-A*00008')->getContent(), true);
    }

    return json_decode(successJsonReturn([
        'version' => $appVersion,
        'buildVersion' => $appBuildVersion,
        'platform' => $appPlatform,
    ])->getContent(), true);
}
/**
 * 验证app状态
 *
 * @return json
 */
function VerifyAppStatus()
{
    /**
     * 获取最新版本的app
     *
     * @param string $version 推荐版本
     * @return json
     */
    function getNewApp($version = null)
    {


        $appPlatform = (Request::header('app-platform')); //app类型 ios android
        if ($version) { //判断有没有推荐版本
            $where = [
                "platform" => ($appPlatform == 'ios') ? 0 : 1,
                "uorce_update" => 0,
                "disable" => 0, //是否禁用
                "version" => $version, //推荐版本
            ];
        } else {
            $where = [
                "platform" => ($appPlatform == 'ios') ? 0 : 1,
                "uorce_update" => 0,
                "disable" => 0, //是否禁用
            ];
        }
        $NewApp =  Db::table('app_info') //查询最新的app
            ->where($where)
            ->field([
                "version", //应用版本
                "download_url", //下载地址
            ])
            ->order('id desc')
            ->find();

        if ($NewApp) {
            return json_decode(successJsonReturn([
                "version" => $NewApp["version"],
                "download_url" => $NewApp['download_url'],
            ])->getContent(), true);
        } else {
            return json_decode(errorJsonReturn('A-10002')->getContent(), true);
        }
    }

    $apiKey = Request::header('api-key'); //接口密钥
    $appPlatform = Request::header('app-platform'); //app类型 ios android
    $appBuildVersion = Request::header('app-build-version'); //app编译版本
    $appUUID = Request::header('app-uuid'); //app的id
    $appVersion = Request::header('app-version'); //app的版本号

    $appInfo =  Db::table('app_info')
        ->where([
            "_id" => $appUUID,
            "key" => $apiKey,
            "platform" => ($appPlatform == 'ios') ? 0 : 1,
            "version" => $appVersion,
            "build_version" => $appBuildVersion,
        ])
        ->field([
            "uorce_update", //是否强制更新
            "minimum_version_number", //强制更新最低版本号
            "download_url", //下载地址
            "private_key", //私钥
            "disable", //是否禁用
            "disable_info", //禁用原因
        ])
        ->order('id desc')
        ->find();
    if (!$appInfo) { //!判断app是否可用
        $NewApp = getNewApp();
        if ($NewApp['code'] == 200) { //判断有没有成功获取最新的信息
            return json_decode(errorJsonReturn("A-10000", false, 0, [
                "msg" => Multilingualism("Other-A*00004") . $NewApp['data']['version'],
                "download_url" => $NewApp['data']['download_url'],
            ])->getContent(), true);
        } else {
            return json_decode(errorJsonReturn("A-10000", false, 0, [
                "msg" =>  Multilingualism("Other-A*00003"),
            ])->getContent(), true);
        }
    }
    if ($appInfo["uorce_update"] == 1) { //!判断app是否需要强制更新
        $RecommendedVersion =  getNewApp($appInfo["minimum_version_number"]);
        if ($RecommendedVersion['code'] == 200) { //判断是否需要强制更新
            return json_decode(errorJsonReturn("A-10001", false, 0, [
                "msg" => Multilingualism("Other-A*00001")  . $RecommendedVersion['data']['version'], //信息
                "download_url" => $RecommendedVersion['data']['download_url'], //推荐版本
            ])->getContent(), true);
        } else { //没有获取到推荐版本
            $NewApp =  getNewApp();
            if ($NewApp['code'] == 200) { //判断有没有获取到最新版本
                return json_decode(errorJsonReturn("A-10001", false, 0, [
                    "msg" => Multilingualism("Other-A*00002")  . $NewApp['data']['version'], //信息
                    "download_url" => $NewApp['data']['download_url'], //推荐版本
                ])->getContent(), true);
            } else {
                return json_decode(errorJsonReturn("A-10000", false, 0, [
                    "msg" =>  Multilingualism("Other-A*00003"),
                ])->getContent(), true);
            }
        }
    }

    if ($appInfo["disable"] == 1) { //!判断app是否被禁用
        $RecommendedVersion =  getNewApp($appInfo["minimum_version_number"]);
        if ($RecommendedVersion['code'] == 200) { //判断是否需要强制更新
            return json_decode(errorJsonReturn("A-10001", false, 0, [
                "msg" => Multilingualism("Other-A*00005") . " $appInfo[disable_info] " . Multilingualism("Other-A*00006")    . $RecommendedVersion['data']['version'], //信息
                "download_url" => $RecommendedVersion['data']['download_url'], //推荐版本
            ])->getContent(), true);
        } else { //没有获取到推荐版本
            $NewApp =  getNewApp();
            if ($NewApp['code'] == 200) { //判断有没有获取到最新版本
                return json_decode(errorJsonReturn("A-10001", false, 0, [
                    "msg" => Multilingualism("Other-A*00005") . " $appInfo[disable_info] "  . Multilingualism("Other-A*00007")  . $NewApp['data']['version'], //信息
                    "download_url" => $NewApp['data']['download_url'], //推荐版本
                ])->getContent(), true);
            } else {
                return json_decode(errorJsonReturn("A-10000", false, 0, [
                    "msg" =>  Multilingualism("Other-A*00003"),
                ])->getContent(), true);
            }
        }
    }
    return json_decode(successJsonReturn([ //验证app通过 返回一个私钥
        "private_key" => $appInfo['private_key'],
    ])->getContent(), true);
}
/**
 * 用户令牌验证
 *
 * @param String $Token
 * @return Json
 * 
 * 使用方法
 *     $userState = UserTokenStateParameterValidation(); //用户令牌验证
 *      if ($userState['code'] != 200) { //验证请求参数
 *          return json($userState); //验证失败返回
 *      }
 */
function UserTokenStateParameterValidation($Token = null)
{
    if (!$Token) {
        $Token = Request::header('Authorization'); //用户token
    }
    $str = explode('.', $Token);
    if (count($str) != 3) { //token为三段 第一段 加密模式 第二段 加密的数据 第三段验证
        return json_decode(errorJsonReturn("T-10000")->getContent(), true);
    }
    $mode = $str[0];
    $encryption = $str[1];
    $verification = hash_hmac("sha512", $encryption, config('apiconfig.TokenResolutionKeySha512')); //待验证令牌的 512
    if ($verification != $str[2]) {
        return json_decode(errorJsonReturn("T-10000")->getContent(), true); //验证的令牌 和 传入的令牌的信息不一致
    }
    //令牌验证通过
    $mode = base64_decode($mode); //解析加密方式 一般没用
    // ^ "{"Encryption":"SHA256","verification":"SHA512"}"
    $encryption = base64_decode($encryption); //现进行base64 解密
    $encryption = json_decode(authcode($encryption, "DECODE", config('apiconfig.TokenResolutionKey')), true); // 在进行 解密
    if ($encryption == null || $encryption == "") { //判断 token 有没有正确解析
        return json_decode(errorJsonReturn('T-10001')->getContent(), true);
    }
    if ($encryption['exp'] <= time()) {
        return json_decode(errorJsonReturn('T-10002')->getContent(), true);
    }
    return json_decode(successJsonReturn($encryption)->getContent(), true);
}

/**
 * 数据库查询用户token
 *
 * @return json
 */
function dataBaseVerificationUser()
{
    $authorization = Request::header('Authorization'); //用户token
    if (!$authorization) { //用户没有传入令牌
        return json_decode(errorJsonReturn("T-10000")->getContent(), true);
    }
    $user_info = Db::table("user_info")
        ->where([
            "to_ken" => $authorization
        ])->select();
    if (count($user_info) > 1 || count($user_info) == 0) {
        return json_decode(errorJsonReturn("T-10001")->getContent(), true);
        // '有多个用户 或没找到用户';
    } else {
        $return =
            ["code" => 200, "_id" => $user_info[0]["_id"]];
    }
    return $return;
}
/**
 * 请求验证 及 用户验证
 *
 * @param app验证 bool $appVersion
 * @param 请求验证 bool $requestVersion
 * @param 用户验证 bool $userVersion
 * @param 数据库验证用户token bool $dataBaseVerificationUser
 * @param 调试模式 bool $debug
 * @return ^ array:3 
 [
  "code" => 200
  "message" => "success"
  "data" => array:4 [
      "panic"=>true,
    "appVersion" => array:3 [ //app版本验证
      "code" => 200
      "message" => "success"
      "data" => array:1 [
          "panic"=>true,
        "private_key" => "DGNMO8NlJw3aqh6opP7gTbpUta23Zk0I4xJthrE0FpB3PKzhinyBsZjYHtXuxEi99lPhfUAGhVUrr5M5OxYtZF3V18G8ZM5AEZmkcaDn3x1rBZPXS5TAynGkhFdZu0pj26uWiSDXiocGoGheZ8DtTE3K2dbKdBKf6OtjfxbVD5hxDRhqkAA34sIBzYRsDPRRiCj2Xn5CNQXxvMSHiEyQMjxpskXuKOFimXr3oG4wjGZIqjcvWg3gM4xwYQ0PLAw"
      ]
    ]
    "requestVersion" => array:3 [ //请求验证
      "code" => 200
      "message" => "success"
      "data" => array:3 [
          "panic"=>true,
        "version" => "2.1.2.6"
        "buildVersion" => "33"
        "platform" => "ios"
      ]
    ]
    "userVersion" => array:3 [ //用户验证
      "code" => 200
      "message" => "success"
      "data" => array:9 [
          "panic"=>true,
        "_id" => "user-wamcxz2zxxu7c598ysz8z0mwfq2bbi0uw50gbm1l23sk1r6z1cmmk98oxqdp5ldr52xbjgvkq4pl5mh66n03525t3vmyzusv61m8lmw9m5tkdd98c28t485m7bho2i89g97e5ioazjjkmig41eyl8ygg3k3sv2zkvcvoqdunfbr11uwqswfvhseu3cto5ooa2xtbkckidkgs6mib57uejaxjdt8cbok10wyt7h3ua3rgyfukbzilw8qpk"
        "email" => "sakura_223@icloud.com"
        "role" => "member"
        "name" => "鞠耀斌"
        "version" => "2.1.2.6"
        "buildVersion" => "33"
        "platform" => "ios"
        "iat" => 1594045649
        "exp" => 1594650449
      ]
    ]
    "dataBaseUserState" => array:2 [ //token 数据库验证
      "code" => 200
      "_id" => "user-wamcxz2zxxu7c598ysz8z0mwfq2bbi0uw50gbm1l23sk1r6z1cmmk98oxqdp5ldr52xbjgvkq4pl5mh66n03525t3vmyzusv61m8lmw9m5tkdd98c28t485m7bho2i89g97e5ioazjjkmig41eyl8ygg3k3sv2zkvcvoqdunfbr11uwqswfvhseu3cto5ooa2xtbkckidkgs6mib57uejaxjdt8cbok10wyt7h3ua3rgyfukbzilw8qpk"
    ]
  ]
]
 * 
 */
function RequestAuthenticationAndUserAuthentication($appVersion = true, $requestVersion = true, $userVersion = true, $dataBaseVerificationUser = true, $debug = false)
{
    $appState = []; //app验证状态
    $requestState = []; //请求验证状态
    $userState = []; //用户验证状态
    $dataBaseUserState = []; //数据库查询用户
    if ($appVersion) {
        $appState  = VerifyAppStatus(); //app 验证
        if ($appState['code'] != 200) { //判断 app验证是否异常 
            #异常直接返回
            if ($debug) {
                dump('发生错误 错误位置 appVersion');
                dump($appState);
                return $appState;
            } else {
                return $appState;
            }
        }
    }

    if ($requestVersion) { //请求验证
        $requestState =  UserRequestParameterValidation($appState['data']['private_key'], $debug); //request请求验证
        if ($requestState['code'] != 200) { //验证请求参数
            if ($debug) {
                dump('发生错误 错误位置 requestVersion');
                dump($requestState);
                return $requestState; //验证失败返回
            } else {
                return $requestState; //验证失败返回
            }
        }
    }

    if ($userVersion) { //用户验证
        $userState = UserTokenStateParameterValidation(); //用户令牌验证
        if ($userState['code'] != 200) { //验证请求参数
            if ($debug) {
                dump('发生错误 错误位置 userVersion');
                dump($userState);
                return $userState; //验证失败返回
            } else {
                return $userState; //验证失败返回
            }
        }
    }
    if ($dataBaseVerificationUser) { //从数据库查询用户token 是否有效
        $dataBaseUserState = dataBaseVerificationUser();
        if ($dataBaseUserState['code'] != 200) {
            if ($debug) {
                var_dump('出错位置 dataBaseVerificationUser');
            }
            return $dataBaseUserState;
        }
        if ($dataBaseUserState['_id'] != $userState['data']['_id']) {
            return json_decode(errorJsonReturn('T-10001', 'token 发生意外错误 请重新登录')->getContent(), true);
        }
    }
    return json_decode(successJsonReturn([

        "appVersion" => $appState,
        "requestVersion" => $requestState,
        "userVersion" => $userState,
        "dataBaseUserState" => $dataBaseUserState,

    ])->getContent(), true);
}
function Multilingualism($StringCode)
{
    $language = Request::header('Accept-Language'); //语言地区
    switch ($language) {
        case 'zh-cn': //中文
            $language = 'lanZhCn';
            break;
        case 'ja-jp': //日语
            $language = 'lanJaJp';
            break;
        case 'zh-tw': //繁体中文
            $language = 'lanZhCn';
            break;
        case 'en-us': //英语
            $language = 'lanEnUs';
            break;
        default: //默认
            $language = 'lanJaJp';
            break;
    }
    return config("$language.$StringCode");
}



/**
 * 发送激活D-Mail
 *
 * @param String $userName 用户名/邮箱
 * @param String $userId 用户id
 * @param String $name 昵称
 * @return bool 是否发送成功
 */
function sendActivation(
    $userName, //用户名
    $userId, //用户id
    $name //昵称
) {
    $domain = request()->domain(); //域名
    // 生成认证URL 分别是 json格式的 time  randStr userName  userId 用 authcode 加密(key1) 并且取加密前的 sha256作为(key2) 加上 随机字符串(key3)
    $key3 = randIdStructure(99999, 254);
    $key1 = json_encode(
        [
            "time" => time() + 172800, //时间戳 时间是2天
            "randStr" => $key3, //加密密钥
            "userName" => $userName, //用户名
            "userId" => $userId, //用户id
            "name" => $name, //昵称
        ]
    );

    $key2 = urlencode(hash_hmac('sha256', $key1, $key3)); //这是加密校验字符串
    $key1 = urlencode(authcode($key1, 'encode', config('globalSettings.api_RegUserAuthcode'))); //这时可悲解密的数据
    $url = $domain . "/api/User/ActivateUser?key1=$key1&key2=$key2";
    $mailHtml = <<<ect
    親愛的 "$name"，<br>
    請按以下連結激活帳號，<br>
    $url/<br>
    (如果您沒有註冊 請不要理會此郵件) <br>
    嗶咔漫畫<br>
    <img style="width:100%;height:auto;" src="https://i0.hdslb.com/bfs/album/619fe3ebc7c8c1f0dcd9494c8c5d2d4b29e60a85.jpg">
ect;
    // echo $url;
    return sendMail($userName, '欢迎注册哔咔漫画', $mailHtml, [
        /*  [
            "fileSrc" => "https://i0.hdslb.com/bfs/album/619fe3ebc7c8c1f0dcd9494c8c5d2d4b29e60a85.jpg",
            "fileName" => 'aaa.jpej',
        ] */]);
}
/**
 * 发送找回密码邮件
 *
 * @param array $user_info
 * @param string $NewPassWord 新密码
 * @return bool
 */
function sendRetrievePassword($user_info, $NewPassWord)
{
    $domain = request()->domain(); //域名
    // 生成认证URL 分别是 json格式的 time  randStr userName  userId 用 authcode 加密(key1) 并且取加密前的 sha256作为(key2) 加上 随机字符串(key3)
    $key3 = randIdStructure(99999, 254);
    $key1 = json_encode(
        [
            "time" => time() + 172800, //时间戳 时间是2天
            "randStr" => $key3, //加密密钥
            "userName" => $user_info['user_name'], //用户名
            "userId" => $user_info['_id'], //用户id
            "name" => $user_info['name'], //昵称
        ]
    );

    $key2 = urlencode(hash_hmac('sha256', $key1, $key3)); //这是加密校验字符串
    $key1 = urlencode(authcode($key1, 'encode', config('globalSettings.api_RegUserAuthcode'))); //这时可悲解密的数据
    Db::table('user_info')
        ->where($user_info)
        ->update([
            "retrieve_password_key1" => $key1,
            "retrieve_password_key2" => $key2,
            "retrieve_password" => $NewPassWord,
        ]);
    $url = $domain . "/api/User/ResetPassword?key1=$key1&key2=$key2";
    $mailHtml = <<<ect
    親愛的 "$user_info[name]"，<br>
    請按以下連結重置帳號，<br>
    $url/<br>
    (如果您沒有重置密码 請不要理會此郵件) <br>
    嗶咔漫畫<br>
    <img style="width:100%;height:auto;" src="https://i0.hdslb.com/bfs/album/619fe3ebc7c8c1f0dcd9494c8c5d2d4b29e60a85.jpg">
ect;
    // echo $url;
    return sendMail($user_info['user_name'], '请使用以下链接找回密码', $mailHtml, [
        /*  [
            "fileSrc" => "https://i0.hdslb.com/bfs/album/619fe3ebc7c8c1f0dcd9494c8c5d2d4b29e60a85.jpg",
            "fileName" => 'aaa.jpej',
        ] */]);
}
